<template>
  <div>
    <el-form :model="formData" label-width="120" :rules="rules" ref="ruleFormRef">
      <el-form-item label="文章标题:" prop="title">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="副标题:" prop="subtitle">
        <el-input v-model="formData.subtitle"></el-input>
      </el-form-item>
      <el-form-item label="引题:" prop="introduction">
        <el-input v-model="formData.introduction"></el-input>
      </el-form-item>
      <el-form-item label="作者:" prop="author">
        <el-input v-model="formData.author"></el-input>
      </el-form-item>
      <el-form-item label="文章内容:" prop="content">
        <div style="border: 1px solid #ccc; margin-top: 10px;">
          <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
              style="border-bottom: 1px solid #ccc"
          />
          <Editor
              :defaultConfig="editorConfig"
              :mode="mode"
              v-model="formData.content"
              style="height: 400px; overflow-y: hidden;"
              @onCreated="handleCreated"
              @onChange="handleChange"
              @onDestroyed="handleDestroyed"
              @onFocus="handleFocus"
              @onBlur="handleBlur"
              @customAlert="customAlert"
              @customPaste="customPaste"
          />
        </div>
      </el-form-item>
    </el-form>

    <div>
      <el-button v-if="currentIndex>0" @click="toPre(ruleFormRef)">返回上一篇</el-button>
      <el-button>{{ currentIndex + 1 }}</el-button>
      <el-button @click="toNext(ruleFormRef)">继续下一篇</el-button>
      <el-button>完成</el-button>
    </div>
  </div>
</template>

<script setup>

import {onBeforeUnmount, ref, shallowRef, onMounted, unref, nextTick} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import indexedDbService from '@/utils/indexedBd.js'
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef()
const formData = ref({
  title: '',
  subtitle: '',
  introduction: '',
  author: '',
  content: ''
})
const mode = ref('default')
const ruleFormRef = ref()
const currentIndex = ref(0)
const rules = ref({
  title: [
    {
      required: true,
      message: '标题不可为空',
      trigger: 'change'
    }
  ]
})
let id = 1
let dataList = []
onMounted(() => {
  initFormData()
})

async function initFormData() {
  const result = await indexedDbService.getItemById(id)
  if (result) {
    dataList = result.dataList || []
    currentIndex.value = dataList[dataList.length - 1]?.index
    formData.value = dataList[currentIndex.value]
  }
}

async function saveFormData(isNext = false) {
  const result = await indexedDbService.getItemById(id)
  const formDataClone = JSON.parse(JSON.stringify(unref(formData)))
  if (result) {
    dataList = result.dataList || []
    const index = dataList.findIndex(item => item?.index === currentIndex.value)
    if (index !== -1) {
      dataList[index] = {...formDataClone, index: currentIndex.value}
      await indexedDbService.updateItem({id, dataList})
    } else {
      // if (isNext) {
      dataList.push({...formDataClone, index: currentIndex.value})
      await indexedDbService.updateItem({id, dataList: dataList})
      // }
    }
  } else {
    dataList.push({...formDataClone, index: currentIndex.value})
    await indexedDbService.addItem({id, dataList: dataList})
  }
}

async function loadFormData(index) {
  const result = await indexedDbService.getItemById(id)
  if (result) {
    dataList = result.dataList || []
    const item = dataList.find(item => item.index === index)
    if (item) {
      formData.value = {...item}
    } else {
      formData.value = {
        title: '',
        subtitle: '',
        introduction: '',
        author: '',
        content: ''
      }
    }
  }
}

async function toPre(formEl) {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await saveFormData()
      currentIndex.value = currentIndex.value - 1
      await loadFormData(currentIndex.value)
    }
  })

}

async function toNext(formEl) {
  console.log(formEl)
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await saveFormData(true)
      currentIndex.value = currentIndex.value + 1
      await loadFormData(currentIndex.value)
    }
  })
  // await saveFormData(true)
  // currentIndex.value = currentIndex.value + 1
  // await loadFormData(currentIndex.value)
}


const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...', MENU_CONF: {
    uploadImage: {
      server: `${import.meta.env.VITE_HTTP_URL}/files/upload`,
      fieldName: 'file',
      customInsert(res, insertFn) {
        // TS 语法
        // customInsert(res, insertFn) {                  // JS 语法
        // res 即服务端的返回结果

        // 从 res 中找到 url alt href ，然后插入图片
        const {etag: url, alt = '描述'} = res
        insertFn(url, alt)
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return

  editor.destroy()
})

// 编辑器回调函数
const handleCreated = (editor) => {
  // console.log('created', editor);
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = (editor) => {
  // console.log('change:', editor.getHtml());
}
const handleDestroyed = (editor) => {
  // console.log('destroyed', editor)
}
const handleFocus = (editor) => {
  // console.log('focus', editor)
}
const handleBlur = (editor) => {
  // console.log('blur', editor)
}
const customAlert = (info, type) => {
  alert(`【自定义提示】${type} - ${info}`)
}
const customPaste = (editor, event, callback) => {
  console.log('ClipboardEvent 粘贴事件对象', event)

  // 自定义插入内容
  // editor.insertText('xxx')

  // 返回值（注意，vue 事件的返回值，不能用 return）
  callback(true) // 返回 false ，阻止默认粘贴行为
  // callback(true) // 返回 true ，继续默认的粘贴行为
}


</script>


<style scoped lang="scss">

</style>